package com.xzz.window;

import java.util.HashSet;

/**
 * @author: hhz
 * @create: 2022-01-19 11:10
 * 219. 存在重复元素 II
 * 给你一个整数数组nums 和一个整数k ，判断数组中是否存在两个 不同的索引i和j ，满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在，返回 true ；否则，返回 false 。
 *
 **/
public class ContainsNearbyDuplicate {
    public static void main(String[] args) {
        System.out.println(containsNearbyDuplicate(new int[]{1,2,3,1},3));
        System.out.println(containsNearbyDuplicate(new int[]{1,0,1,1},1));
        System.out.println(containsNearbyDuplicate(new int[]{1,2,3,1,2,3},2));
    }
    public static boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> window = new HashSet<>();
        int left = 0;
        int right = 0;

        while (right<nums.length){
            int num = nums[right];
            right++;
            if(!window.add(num)){
                return true;
            }
            while (right-left>k){
                window.remove(nums[left]);
                left++;
            }
        }
        return false;
    }
}
